package com.controller;


import com.entity.Cart;
import com.service.CartService;
import com.util.StatusCode;
import com.vo.CartVO;
import com.vo.LayuiPageVo;
import com.vo.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * <p>
 *  购物车逻辑
 *  - 添加购物车---放入缓存；
 *  - 查看购物车---查看redis缓存
 * </p>
 *
 * @author hlt
 * @since 2019-12-21
 */
@Controller
@Api(value = "购物车管理")
public class CartController {
    @Autowired
    private CartService cartService;

    @Autowired
    RedisTemplate redisTemplate;

    public static String CART_KEY;

    /**
     * 商品详情界面：添加购物车
     * 获取session中用户id信息，判断是否登录
     * (1). 添加购物车
     * 1.前端传入商品id（commid）、商品用户id（cmuserid）、
     *   商品数量（count）、购物车小计
     * 2.session中获取收藏用户id（couserid）
     */
    @ResponseBody
    @ApiOperation(value = "添加购物车")
    @PostMapping("/cart/operate")
    public ResultVo insertcart(@RequestBody Cart cart, HttpSession session){
        String uId = (String) session.getAttribute("userid");
        cart.setUId(uId);
        if (StringUtils.isEmpty(uId)){
            return new ResultVo(false, StatusCode.ACCESSERROR,"请先登录");
        }
        int insert = cartService.insert(cart);
        if(insert == 1){
            return new ResultVo(true, StatusCode.OK,"添加成功");
        }else {
            return  new ResultVo(false, StatusCode.ERROR,"添加失败");
        }
    }

    /**
     * 收藏列表界面取消收藏
     * 1.前端传入收藏id（id）
     * 2.判断是否本人取消收藏
     * 3.进行取消收藏操作
     */
    @ResponseBody
    @ApiOperation("删除购物车")
    @PutMapping("/cart/delete/{cid}")
    public ResultVo deletecart(@PathVariable("cid") Integer cid,HttpSession session){
        String couserid = (String) session.getAttribute("userid");
        Cart cart1 = cartService.selectByPrimaryKey(cid);

        /**判断是否为本人操作*/
        if (cart1.getUId().equals(couserid)){
             int i = cartService.deleteByPrimaryKey(cid);
            if (i == 1){
                return new ResultVo(true, StatusCode.OK,"删除成功");
            }
            return new ResultVo(false,StatusCode.ERROR,"删除失败");
        }
        return new ResultVo(false,StatusCode.ACCESSERROR,"禁止操作");
    }

    /**
     * 分页查看用户所有收藏内容
     * 前端传入页码、分页数量
     * 查询分页数据
     */
    @ResponseBody
    @ApiOperation("查询购物车")
    @GetMapping("/user/cart/queryall")
    public LayuiPageVo userCart(int limit, int page, HttpSession session) {
        String couserid = (String) session.getAttribute("userid");
        List<CartVO> carts = cartService.queryAllCart((page - 1) * limit, limit, couserid, CartController.CART_KEY);
//        List<Object> values = stringRedisTemplate.opsForHash().values(couserid);
        Integer dataNumber = carts.size();
        return new LayuiPageVo("",0,dataNumber,carts);
    }

    @ResponseBody
    @ApiOperation("更新购物车")
    @PostMapping("/user/cart/update/{num}/{cid}")
    public ResultVo updateCart(@PathVariable("num") int num, @PathVariable("cid") Integer cid, HttpSession session){
        String couserid = (String) session.getAttribute("userid");
        Cart cart = new Cart();
        cart.setUId(couserid).setCNum(num);
        cart.setCId(cid);
        int i = cartService.updateCart(cart);
        if(i == 1){
            return new ResultVo(true, StatusCode.OK,"修改成功");
        }else{
            return new ResultVo(false, StatusCode.ERROR,"修改失败");
        }
    }
}